package cc.shacocloud.mirage.bean.meta;

import cc.shacocloud.mirage.utils.ClassUtil;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Constructor;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * {@link BeanConstructor} 默认实现
 *
 * @author 思追(shaco)
 */
public class BeanConstructorImpl implements BeanConstructor {
    
    @NotNull
    @Getter
    private final Constructor<?> constructor;
    
    @NotNull
    private final List<BeanKey> dependencies;
    
    public BeanConstructorImpl(@NotNull Constructor<?> constructor,
                               @NotNull List<BeanKey> dependencies) {
        this.constructor = constructor;
        this.dependencies = dependencies;
    }
    
    /**
     * 使用指定的参数调用此构造函数，并返回新实例。支持具有任何访问修饰符的构造函数。
     */
    @Override
    public Object createInstance(@NotNull Object[] parameters) {
        return ClassUtil.instantiateClass(constructor, parameters);
    }
    
    /**
     * 获取依赖对象
     */
    @NotNull
    @Override
    public List<BeanKey> getDependencies() {
        return Collections.unmodifiableList(dependencies);
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BeanConstructorImpl that = (BeanConstructorImpl) o;
        return constructor.equals(that.constructor) && dependencies.equals(that.dependencies);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(constructor, dependencies);
    }
}
